package com.wpre.lotterysystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wpre.lotterysystem.common.pojo.CommonResult;
import org.apache.el.util.ReflectionUtil;
import org.springframework.boot.json.JsonParseException;
import org.springframework.util.ReflectionUtils;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * Created with IntelliJ IDEA.
 * Description: 自定义序列化工具
 * User: LianBao
 * Date: 2024-12-11
 * Time: 13:46
 */
public class JacksonUtil {
    private JacksonUtil() {

    }

    /**
     * 对ObjectMapper进行单例化
     */
    private final static ObjectMapper OBJECT_MAPPER;

    static {
        //实例化
        OBJECT_MAPPER = new ObjectMapper();
    }

    private static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    private static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }


    //借鉴SpringBoot统一异常
    //Callable<T> parser,这个参数,支持我们使用lambda表达式进行处理
    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            Exception ex = var4;
            if (check.isAssignableFrom(ex.getClass())) {
                throw new JsonParseException(ex);
            }
            throw new IllegalStateException(ex);
        }
    }


    /**
     * 序列化方法
     *
     * @param o
     * @return
     */
    public static String writeValueAsString(Object o) {
        return JacksonUtil.tryParse(() -> {
            //执行序列化的操作
            //如果此处出现异常,直接会在tryParse这里捕获
            return JacksonUtil.getObjectMapper().writeValueAsString(o);
        });
    }


    /**
     * 反序列化Object方法
     *
     * @param content
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T readValue(String content, Class<T> valueType) {
        return JacksonUtil.tryParse(() -> {
            return JacksonUtil.getObjectMapper().readValue(content, valueType);
        });
    }

    /**
     * 反序列化List
     *
     * @param content
     * @param paramClasses
     * @param <T>
     * @return
     */
    public static <T> T readListValue(String content, Class<?> paramClasses) {

        //1.构造JavaType
        JavaType javaType = JacksonUtil.getObjectMapper().
                getTypeFactory().//获取类型工厂
                        constructParametricType(List.class, paramClasses);//构造List的类型

        //2.反序列化
        return JacksonUtil.tryParse(() -> {
            return JacksonUtil.getObjectMapper().readValue(content, javaType);
        });

    }

}
